#include "stdafx.h"
#include "FormDataLua.h"


namespace FormDataLua
{

	bool push(lua_State* L, Forms* pFormData)
	{
		Forms** pp = (Forms**)lua_newuserdata(L, sizeof(Forms*));
		*pp = pFormData;
		luaL_getmetatable(L, "woe.FormData");
		if (lua_istable(L, -1))
		{
			lua_setmetatable(L, -2);
			return true;
		}
		else
		{
			LOG_ERROR("Failed to push FormData to lua, metatable not found!");
			return false;
		}
	}

	Forms* getUserData(lua_State* L)
	{
		Forms**pp = (Forms**)luaL_checkudata(L, 1, "woe.FormData");
		if (pp==NULL)
		{
			return NULL;
		}
		else
		{
			return *pp;
		}
	}

	int setSlot(lua_State* L)
	{
		Forms* pFormData = getUserData(L);
		if (pFormData)
		{
			short ftype = (short)luaL_checkint(L, 2);
			short fslot = (short)luaL_checkint(L, 3);
			short rid = (short)luaL_checkint(L, 4);

			if (ftype>=0 && 
				ftype<10 &&
				fslot>0 &&
				fslot<6)
			{
				pFormData->forms[ftype-1].set(fslot-1, rid);
			}
		}
		return 0;
	}

	int getSlot(lua_State* L)
	{
		Forms* pFormData = getUserData(L);
		if (pFormData)
		{
			short ftype = (short)luaL_checkint(L, 2);
			short fslot = (short)luaL_checkint(L, 3);

			if (ftype>=0 && 
				ftype<10 &&
				fslot>0 &&
				fslot<6)
			{
				lua_pushinteger(L, pFormData->forms[ftype-1].get(fslot-1));
				return 1;
			}
		}
		return 0;
	}

	int setLevel(lua_State* L)
	{
		Forms* pFormData = getUserData(L);
		if (pFormData)
		{
			short ftype = (short)luaL_checkint(L, 2);
			short flvl = (short)luaL_checkint(L, 3);

			if (ftype>=0 && 
				ftype<10)
			{
				pFormData->forms[ftype-1].flvl = flvl;
			}
		}
		return 0;
	}

	int getLevel(lua_State* L)
	{
		Forms* pFormData = getUserData(L);
		if (pFormData)
		{
			short ftype = (short)luaL_checkint(L, 2);

			if (ftype>=0 && 
				ftype<10)
			{
				lua_pushinteger(L, pFormData->forms[ftype-1].flvl);
				return 1;
			}
		}
		return 0;
	}

	int setActive(lua_State* L)
	{
		Forms* pFormData = getUserData(L);
		if (pFormData)
		{
			short ftype = (short)luaL_checkint(L, 2);

			if (ftype>=0 && 
				ftype<10)
			{
				pFormData->ftype = ftype;
			}
		}
		return 0;
	}

	int getActive(lua_State* L)
	{
		Forms* pFormData = getUserData(L);
		if (pFormData)
		{
			lua_pushinteger(L, pFormData->ftype);
		}
		return 0;
	}




	static const luaL_Reg FormData_funcs[] = {
		{"setSlot", setSlot},
		{"getSlot", getSlot},
		{"setLevel", setLevel},
		{"getLevel", getLevel},
		{"getActive", getActive},
		{"setActive", setActive},
		{NULL, NULL}
	};


	int libaray(lua_State* L)
	{
		luaL_newmetatable(L, "woe.FormData");
		// fill member list into metatable
		luaL_register(L, NULL, FormData_funcs);

		// metatable.__index = metatable
		lua_pushstring(L, "__index");
		lua_pushvalue(L, -2);
		lua_settable(L, -3);

		return 0;
	}

} // end of FormData lua
